package cn.loioi.multi.common;

import java.lang.reflect.Field;
import java.util.List;

import javax.persistence.Column;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.pagehelper.PageHelper;

import cn.loioi.util.page.JqGrid;
import cn.loioi.util.page.PageUtil;
import cn.loioi.util.page.query.Sort;
import cn.loioi.util.page.query.where.QueryFilter;
import cn.loioi.util.page.query.where.QueryGroup;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 通用service实现类
 * @文件 :BaseServiceImpl.java
 * @作者 :cn.loioi
 * @创建时间 :2016年10月13日 下午1:24:27
 */
public abstract class BaseServiceImpl<T> implements BaseService<T> {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 查询全部数据
	 */
	@Override
	public List<T> selectAll() {
		return mapper().selectAll();
	}

	/**
	 * 根据条件查询列表
	 * @param example
	 * @return
	 */
	@Override
	public List<T> selectByExample(Example example) {
		return mapper().selectByExample(example);
	}

	/**
	 * 根据Jqgrid自带的查询进行查询
	 * @param jqGrid
	 * @return
	 */
	@Override
	public List<T> selectByJqGrid(JqGrid<T> jqGrid) {
		Example example = new Example(getGenericSuperclass());
		Criteria criteria = example.createCriteria();
		for (QueryFilter filter : jqGrid.getQueryFilters()) {
			Criteria criteria2 = (QueryGroup.AND.equals(filter.getQueryGroup()) ? criteria : example.or());
			switch (filter.getQueryRule()) {
			case EQ:
				criteria2.andEqualTo(filter.getField(), filter.getData());
				break;
			case NE:
				criteria2.andNotEqualTo(filter.getField(), filter.getData());
				break;
			case BW:
				criteria2.andGreaterThanOrEqualTo(filter.getField(), filter.getData());
				break;
			case BN:
				criteria2.andGreaterThan(filter.getField(), filter.getData());
				break;
			case EW:
				criteria2.andLessThanOrEqualTo(filter.getField(), filter.getData());
				break;
			case EN:
				criteria2.andLessThan(filter.getField(), filter.getData());
				break;
			case CN:
				criteria2.andLike(filter.getField(), "%" + filter.getDataStr() + "%");
				break;
			case NC:
				criteria2.andNotLike(filter.getField(), "%" + filter.getDataStr() + "%");
				break;
			case NU:
				criteria2.andIsNotNull(filter.getField());
				break;
			case NN:
				criteria2.andIsNull(filter.getField());
				break;
			case IN:
				criteria2.andIn(filter.getField(), filter.getDataArray());
				break;
			case NI:
				criteria2.andNotIn(filter.getField(), filter.getDataArray());
				break;
			case NONE:
				criteria2.andCondition(filter.getField(), filter.getData());
				break;
			default:
				break;
			}
		}
		setPage(jqGrid);
		return selectByExample(example);
	}

	/**
	 * 根据ID查询一条数据
	 */
	@Override
	public T findByPrimaryKey(Object id) {
		if (isNull(id)) return null;
		return mapper().selectByPrimaryKey(getKey(id));
	}

	/**
	 * 根据条件查询一条记录
	 * @param example
	 * @return
	 */
	@Override
	public T findByExample(Example example) {
		List<T> list = selectByExample(example);
		return list.isEmpty() ? null : list.get(0);
	}

	/**
	 * 插入一条数据
	 */
	@Override
	public int insert(T record) {
		if (record == null) return 0;
		return mapper().insertSelective(record);
	}

	/**
	 * 更新一条数据
	 */
	@Override
	public int update(T record) {
		if (record == null) return 0;
		return mapper().updateByPrimaryKeySelective(record);
	}

	/**
	 * 删除一条数据
	 */
	@Override
	public int delete(Object id) {
		if (isNull(id)) return 0;
		return mapper().deleteByPrimaryKey(getKey(id));
	}

	/**
	 * 设置分页信息
	 * @param page
	 */
	@Override
	public void setPage(PageUtil page) {
		// 设置页面
		PageHelper.startPage(page.getPageNo(), page.getPageSize(), page.isCount());
		// 判断是否需要排序
		String orderFeild = orderBy(page.sort());
		if (StringUtils.isNotEmpty(orderFeild)) PageHelper.orderBy(orderFeild);
	}

	/**
	 * 获取Mapper实例
	 * @return
	 */
	protected abstract Mapper<T> mapper();

	/**
	 * 获取形参
	 * @return
	 */
	protected abstract Class<T> getGenericSuperclass();

	/**
	 * 获取主键值
	 * @param id
	 * @return
	 */
	protected Object getKey(Object obj) {
		if (isNull(obj)) return null;
		return Integer.valueOf(obj.toString());
	}

	/**
	 * 判断obj是否为空
	 * @param obj
	 * @return
	 */
	protected boolean isNull(Object obj) {
		return obj == null || StringUtils.isEmpty(obj.toString());
	}

	/**
	 * 传入字段获取数据库字段
	 * @param sort
	 * @return
	 */
	private String orderBy(Sort sort) {
		if (sort != null && !sort.empty()) {
			try {
				Field field = getGenericSuperclass().getDeclaredField(sort.sort());
				if (field != null) return sort.toString(field.getAnnotation(Column.class));
			} catch (Exception e) {
			}
		}
		return null;
	}
}
